<?php
namespace App\Libs\Helper;
use App\Libs\Remote\Remote;

class CommonHelper{
	/**
	*	下载pdf
	*/
	public static function downPdf($url, $file="", $timeout=60){
		//$file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
		//$fileName = '/uploadsIns/'.time().rand(10,99).rand(10,99).rand(10,99).".pdf";
		$fileName = '/uploads/'.time().rand(10,99).rand(10,99).rand(10,99).".pdf";
		//$fileName = '/uploadsIns/'.date('Ymd').'/'.time().rand(10,99).rand(10,99).rand(10,99).".pdf";
		$file = APP_PATH.'/public/'.$fileName;
		//$dir = APP_PATH.'/uploadsIns/'.date('Ymd');
		$dir = APP_PATH.'/public/uploads/';
		
		//!is_dir($dir) && @mkdir($dir,0755,true);
		$url = str_replace(" ","%20",$url);
		if(function_exists('curl_init')) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
			$temp = curl_exec($ch);
			if(@file_put_contents($file, $temp) && !curl_error($ch)) {
				//return PASSPORT_DOMAIN.$fileName;
				return $fileName;
			} else {
				//var_dump( curl_error($ch) );
				return false;
			}
		} else {
			$opts = array(
				"http"=>array(
				"method"=>"GET",
				"header"=>"",
				"timeout"=>$timeout)
			);
			$context = stream_context_create($opts);
			if(@copy($url, $file, $context)) {
			//$http_response_header
				return $fileName;
			} else {
				return false;
			}
		}
	}
	
	/**
	*	年龄解析
	*/
	public static function age($birthday){ 
		  $age = strtotime($birthday); 
		  if($age === false){ 
			return ''; 
		  } 
		  list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age)); 
		  $now = strtotime("now"); 
		  list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now)); 
		  $age = $y2 - $y1; 
		  if((int)($m2.$d2) < (int)($m1.$d1)) 
			$age -= 1; 
		  return $age; 
	} 
	
	/**
	*	身份证解析
	*/
	public static function identityInfo( $idcard ){
		if( strlen( $idcard ) == 15 ){
			$idcard = self::getIDCard( $idcard );
		}
		$birth = date("Y-m-d",strtotime( substr($idcard, 6, 8) ));
		$sex = substr($idcard, -2 , 1) % 2 ? '1' : '2'; //1为男 2为女
		return ['birth'=>$birth,'sex'=>$sex];
	}
	
	
	/**
	*	数字切换
	*/
	public static function changeNum( $num ){
		$arr = array('1'=>'一', '2'=>'二' , '3'=>'三' , '4'=>'四' , '5'=>'五' , '6'=>'六' , '7'=>'日'  );
		return $arr[$num];
	}
	
	/**
	*	获取随机字符串	
	*/
	public static function randomChat( $len = 6 , $prefix = '家长家' , $chars = null )
    {
         if (is_null($chars)){
             $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
         }  
         mt_srand(10000000*(double)microtime());
         for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
             $str .= $chars[mt_rand(0, $lc)];  
         }
         return $prefix.$str;
    }
	
	/**
     * 功能：把15位身份证转换成18位
     *
     * @param string $idCard
     * @return newid or id
     */
    public static function getIDCard($idCard) {
        // 若是15位，则转换成18位；否则直接返回ID
        if (15 == strlen( $idCard )) {
            $W = array (7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1 );
            $A = array ("1","0","X","9","8","7","6","5","4","3","2" );
            $s = 0;
            $idCard18 = substr ( $idCard, 0, 6 ) . "19" . substr ( $idCard, 6 );
            $idCard18_len = strlen ( $idCard18 );
            for($i = 0; $i < $idCard18_len; $i ++) {
                $s = $s + substr ( $idCard18, $i, 1 ) * $W [$i];
            }
            $idCard18 .= $A [$s % 11];
            return $idCard18;
        } else {
            return $idCard;
        }
    }
	
	/**
	*	计算两个经纬度之前的距离
	* @param float $lat 纬度值 
	* @param float $lon 经度值
	*/
	public static function getDistance($lat1, $lon1, $lat2, $lon2, $radius=6378.135) 
	{ 
		$rad = doubleval(M_PI/180.0);

		$lat1 = doubleval($lat1) * $rad;
		$lon1 = doubleval($lon1) * $rad;
		$lat2 = doubleval($lat2) * $rad;
		$lon2 = doubleval($lon2) * $rad;

		$theta = $lon2 - $lon1;
		$dist = acos(sin($lat1) * sin($lat2) + 
					cos($lat1) * cos($lat2) * cos($theta));
		if($dist < 0) {
		  $dist += M_PI;
		}
		// 单位为 米
		$distance = $dist * $radius * 1000;
		if($distance < 1000 ){
			return $distance.'m';
		}else{
			return number_format(($distance/1000),2,'.','').'km';
		}
    }

    /**
     * @param $resultArray  查询结果集
     * @param $keyCol   指定为键的列名称
     * @return mixed  返回指定键为键的数组；
     */
    public static function setColToKey($resultArray, $keyCol)
    {
	if( empty($resultArray) ){
		return array();
	}
        foreach ($resultArray as $val) {
            $result[$val[$keyCol]] = $val;
        }
        return $result;
    }
	
	/**
	*	转换距离并加单位
	*	@param $distance 距离
	*/
	public static function transformDis( $distance ){
		if( is_numeric( $distance ) ){
			if( $distance < 1000 ){
				return $distance . 'm';
			}else{
				return  number_format(($distance / 1000) , 2 , '.' , '').'Km';
			}
		}
		return 0 . 'm';
	}
	
	/**
	*	计算两个时间之前的差
	*	@param $begin_time 开始时间
	*	@param $end_time 结束时间
	*/
	public static function timediff( $begin_time, $end_time )  
	{  
	  if ( $begin_time < $end_time ) {  
		$starttime = $begin_time;  
		$endtime = $end_time;  
	  } else {  
		$starttime = $end_time;  
		$endtime = $begin_time;  
	  }  
	  $timediff = $endtime - $starttime;  
	  $days = intval( $timediff / 86400 );  
	  $remain = $timediff % 86400;  
	  $hours = intval( $remain / 3600 );  
	  $remain = $remain % 3600;  
	  $mins = intval( $remain / 60 );  
	  $secs = $remain % 60;  
	  $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );  
	  return $res;  
	}  
	
	
	/**
	*	文件上传
	*/
	public static function fileUpload($files){
		$fileMulu = '';
		$data = array();
			$filepath = '';
            $sid = date("YmdHis").mt_rand(1000, 9999);
            $types = ['png','jpg','jpeg','JPEG','JPG','PNG'];
            //$files = $this->request->getUploadedFiles();
            // Print the real file names and sizes
            foreach ($files as $k=>$file) {
				if(empty( $file->getName() ) ){
					continue;
				}
                if(!in_array($file->getExtension(),$types)){
                    return \App\Libs\Views\Json::view(1, '上传类型错误', NULL); 
                }
				$filename = $sid . $k . '.' . $file->getExtension();
                $filepath = '/uploads/'.$fileMulu . $filename;
                $file->moveTo(APP_PATH.'/public/'.$filepath);
				
				$data[$k]['uri'] = PASSPORT_DOMAIN.$filepath;
                $data[$k]['name'] = $file->getName();
            }
		return $data;
	}
}
